package baseDao;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;
/**
 * Created by 周志聪 on 2019/1/21.
 */
public class baseDao {
    private static String driver;
    private static String url;
    private static String user;
    private static String pwd;
    Connection coon=null;
    static{
        init();
    }
    public static void init(){
        Properties ps=new Properties();
        String cofile="database.properties";
        InputStream is=baseDao.class.getClassLoader().getResourceAsStream(cofile);
        try {
            ps.load(is);
        } catch (Exception e) {
            // TODO: handle exception
        }
        driver=ps.getProperty("driver");
        url=ps.getProperty("url");
        user=ps.getProperty("user");
        pwd=ps.getProperty("pwd");

    }
    public Connection getConnection(){
        try {
            Class.forName(driver);
            coon=DriverManager.getConnection(url, user, pwd);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return coon;
    }
    public void closeAll(Connection conn,PreparedStatement pre,ResultSet set){
        try {
            if (set!=null) {
                set.close();
            }
            if (pre!=null) {
                pre.close();
            }
            if (coon!=null) {
                coon.close();
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
    public int excuteUpdate(String sql,Object[]obj){
        PreparedStatement pre=null;
        int num=0;
        coon=getConnection();
        try {
            pre=coon.prepareStatement(sql);
            if (obj!=null) {
                for (int i = 0; i < obj.length; i++) {
                    pre.setObject(i+1, obj[i]);
                }
            }
            num=pre.executeUpdate();
        } catch (Exception e) {
            // TODO: handle exception
        }finally{
            closeAll(coon, pre, null);
        }
        return num;
    }

    public ResultSet find(String sql,Object[]obj){
        PreparedStatement pre=null;
        int num=0;
        ResultSet set=null;
        coon=getConnection();
        try {
            pre=coon.prepareStatement(sql);
            if (obj!=null) {
                for (int i = 0; i < obj.length; i++) {
                    pre.setObject(i+1, obj[i]);
                }
            }
            set=pre.executeQuery();
        } catch (Exception e) {
            // TODO: handle exception
        }
        return set;
    }





}
